package handle

import (
	"github.com/gin-gonic/gin"
	"img/model"
	"strconv"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	if title == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
	}
	data := model.Article{
		Title:   title,
		Content: content,
	}
	model.DB.Debug().Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	var articles []model.Article
	offset := (page - 1) * size
	model.DB.Offset(offset).Limit(size).Find(&articles)
	var total int64
	model.DB.Model(&model.Article{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "获取成功",
		"total": total,
		"data":  articles,
	})
}

// SELECT articles.title,articles.content,users.username FROM articles JOIN users ON articles.user_id = users.id
func ArticleList(c *gin.Context) {
	var articleList []model.ArticleList
	var article model.Article
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	model.DB.Model(&model.Article{}).Where("articles.title like ?", "%"+article.Title+"%").Select("articles.id,articles.title,articles.content,users.username").
		Joins("JOIN users ON articles.user_id = users.id").Offset(offset).Limit(page).Find(&articleList)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		//"total": total,
		"data": articleList,
	})
}
